<?php
require_once(dirname(__FILE__)."/jsonwrapper/jsonwrapper.php");
include_once(dirname(__FILE__)."/Cache.php");

define("OK", 200);
define("FILE_EXPIRED", 500);
define("FILE_NOT_EXISTS", 501);

class DiskSearch {
	var $_hosts   = array(
	"api.seekdisk.com"
	);

	var $_cache   = null;
	var $_service = "/service.php";
	var $_appid   = "";
	var $_appkey  = "";
	var $_format  = "json";
	var $_version = "1.0";
	var $_debug   = false;
	var $_cpath   = "cache/";
	var $_error   = array();

	function DiskSearch() {
		$this->_cpath  = dirname(__FILE__)."/cache/";
		$this->_cache = Cache::getInstance($this->_cpath);
		
		if(false === ($config = $this->getConfig())) {
			exit("请到http://".$this->_hosts[0]."提交申请，并将配置文件下载并上传到".$this->_cpath."目录下");
		}
		
		$config = $this->getConfig();
		
		$this->_appid  = $config["appid"];
		$this->_appkey = $config["appkey"];
		
		if(!file_exists($this->_cpath) || !is_writable($this->_cpath)) {
			exit("请创建缓存目录{$this->_cpath}并设置权限为777 <a href=\"{$_SERVER['REQUEST_URI']}\">刷新</a>");
		}
	}

	function setFormat($format) {
		$this->_format = $format;
		return true;
	}
	
	function getConfig($refresh = false) {
		$key = "config";
		
		if($refresh || false === ($arr_config_list = $this->_cache->get($key))) {
			$result = $this->getResults("config");

			if($result->status != OK) {
				return array();
			}

			if($arr_config_list = $result->data) {
				$this->_cache->set($key, $arr_config_list);
			}
		}
		
		return is_array($arr_config_list) ? $arr_config_list : false;
	}
	
	function getTotal($refresh = false) {
		$key = "total";

		if($refresh || false === ($total = $this->_cache->get($key))) {
			$result = $this->getResults("total");

			if($result->status != OK) {
				return 0;
			}

			if($total = $result->data) {
				$this->_cache->set($key, $total, 5 * 60);
			}
		}

		return $total;
	}

	function getSearchResults($word, $page = 1, $num = 10, $site = array(), $order = 1, $pos = 1, $size = 1, $cate = 0) {
		$params = "word=$word&page=$page&num=$num";

		foreach ($site as $val) {
			$params .= "&site[]=$val";
		}

		$params.= "&order=$order&pos=$pos&size=$size&cate=$cate";

		$result = $this->getResults("search", $params);

		if($result->status != OK) {
			return false;
		}

		return $result->data;
	}

	function getFileInfo($fid) {
		return $this->getResults("detail", "fid=$fid");
	}

	function getHotSearches($n = 200, $refresh = false) {
		$key = "hotsearches";

		if($refresh || false === ($arr_searches_list = $this->_cache->get($key))) {
			$result = $this->getResults("hotsearches", "count=$n");

			if($result->status != OK) {
				return array();
			}

			if($arr_searches_list = $result->data) {
				$this->_cache->set($key, $arr_searches_list, 3 * 60 * 60);
			}
		}

		return array_slice($arr_searches_list, 0, $n);;
	}

	function getHotFiles($n = 200, $refresh = false) {
		$key = "hotfiles";
		if($refresh || false === ($arr_files_list = $this->_cache->get($key))) {
			$result = $this->getResults("hotfiles", "count=$n");

			if($result->status != OK) {
				return array();
			}

			if($arr_files_list = $result->data) {
				$this->_cache->set($key, $arr_files_list, 3 * 60 * 60);
			}
		}

		return array_slice($arr_files_list, 0, $n);;
	}

	function getLastSearches($n = 200, $refresh = false) {
		$key = "lastsearches";

		if($refresh || false === ($arr_searches_list = $this->_cache->get($key))) {
			$result = $this->getResults("lastsearches", "count=$n");

			if($result->status != OK) {
				return array();
			}

			if($arr_searches_list = $result->data) {
				$this->_cache->set($key, $arr_searches_list, 3 * 60 * 60);
			}
		}

		return array_slice($arr_searches_list, 0, $n);
	}

	function getLastDownloads($n = 200, $refresh = false) {
		$key = "lastdownloads";
		if($refresh || false === ($arr_files_list = $this->_cache->get($key))) {
			$result = $this->getResults("lastdownloads", "count=$n");

			if($result->status != OK) {
				return array();
			}

			if($arr_files_list = $result->data) {
				$this->_cache->set($key, $arr_files_list, 3 * 60 * 60);
			}
		}

		return array_slice($arr_files_list, 0, $n);
	}

	function getDiskFilter($refresh = false) {
		$key = "filter_disk";
		if($refresh || false === ($arr_disk_list = $this->_cache->get($key))) {
			$result = $this->getResults("fdisk");

			if($result->status != OK) {
				return array();
			}

			if($arr_disk_list = $result->data) {
				$this->_cache->set($key, $arr_disk_list, 24 * 60 * 60 * 3);
			}
		}

		return $arr_disk_list;
	}

	function getSortFilter($refresh = false) {
		$key = "filter_sort";
		if($refresh || false === ($arr_sort_list = $this->_cache->get($key))) {
			$result = $this->getResults("fsort");

			if($result->status != OK) {
				return array();
			}

			if($arr_sort_list = $result->data) {
				$this->_cache->set($key, $arr_sort_list, 24 * 60 * 60 * 3);
			}
		}

		return $arr_sort_list;
	}

	function getSizeFilter($refresh = false) {
		$key = "filter_size";
		if($refresh || false === ($arr_size_list = $this->_cache->get($key))) {
			$result = $this->getResults("fsize");

			if($result->status != OK) {
				return array();
			}

			if($arr_size_list = $result->data) {
				$this->_cache->set($key, $arr_size_list, 24 * 60 * 60 * 3);
			}
		}

		return $arr_size_list;
	}

	function setDebug($debug) {
		$this->_debug = $debug;
	}

	function getHostName() {
		$hosts = $this->getHostList();

		return is_array($hosts) && !empty($hosts) ? current($hosts) : false;
	}

	function getHostList($refresh = false) {
		$key = "hosts";

		if($refresh || false === ($arr_host_list = $this->_cache->get($key))) {
			$result = $this->getResults("hosts");

			if($result->status != OK) {
				return array();
			}

			if($arr_host_list = $result->data) {
				$this->_cache->set($key, $arr_host_list, 24 * 60 * 60 * 7);
			}
		}

		return is_array($arr_host_list) ? array_unique(array_merge($arr_host_list, $this->_hosts)) : $this->_hosts;
	}

	function getError() {
		return $this->_error;
	}

	function getResults($source, $params = "") {
		if(false == $hosts = $this->_cache->get($key)) {
			$hosts = $this->_hosts;
		}

		$url = $this->_service."?appid=".$this->_appid."&appmd=".urlencode(md5($this->_appid, $this->_appkey))."&format=".$this->_format."&version=".$this->_version;
		$url.= "&source=$source";
		$url.= $params ? "&".$params : "";

		if($this->_debug) {
			print "service full path:http://".$hosts[0].$url."\n";
		}

		$content = "";
		foreach ($hosts as $host) {
			$fp = @fsockopen($host, 80, &$errno, &$errstr, 5);

			if ($fp) {
				$out = "GET $url HTTP/1.1\r\n";
				$out .= "Host: $host\r\n";
				$out .= "Connection: Close\r\n\r\n";
				fwrite($fp, $out);

				$header = true;
				do {
					//skip header
					if($header) {
						$line = fgets($fp, 1024);

						if($line == "\r\n") {
							$header = false;
							$line = fgets($fp, 1024);
						}

						continue;
					}

					$line = trim(fgets($fp, 1024));

					//skip end
					if($line) {
						$content .= $line;
					}
				} while (!feof($fp));

				fclose($fp);
			}

			if(!$content) {
				exit("请将SDK更新到最新版本![http://code.google.com/p/disksearch/downloads/list]");
				return false;
			}

			$result = json_decode($content);

			return $result;
		}
	}
}
?>